package cn.tangsihai.basic.util;


import cn.tangsihai.user.domain.Logininfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 从请求头中获取用户登录信息
 */
public class LoginContextUtil {
    public static Logininfo getLoginContext(){
        // 请求: RequestContextHolder是SpringMVC中的一个请求上下文工具，里面有ServletRequestAttributes
        // 而：ServletRequestAttributes里面有请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //拿到请求对象
        HttpServletRequest request = requestAttributes.getRequest();
        return getLoginContext(request);
    }

    public static Logininfo getLoginContext (HttpServletRequest request){
        String token = request.getHeader("token"); // 获取请求头中的token
        if (!StringUtils.isEmpty(token)){
            //1 获取spring容器
            WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            //2 通过容器获取bean
            RedisTemplate redisTemplate = (RedisTemplate) context.getBean("redisTemplate");
            // 3.使用token从redis中获取用户消息。
            Object strObj = redisTemplate.opsForValue().get(token);
            if (strObj != null){
                return (Logininfo) strObj;
            }
        }
        return null;
    }
}
